<template>
    <div class="map-page">
        <!-- 地图容器 -->
        <div ref="mapContainer" class="map-container"></div>

        <!-- 控件显示容器 -->
        <div id="scale-line" class="control-display" :style="{ display: scaleVisible ? 'block' : 'none' }">
            {{ scaleText }}
        </div>
        <div id="mouse-position" class="control-display" :style="{ display: mousePositionVisible ? 'block' : 'none' }">
            {{ mousePositionText }}
        </div>

        <!-- 自定义控制面板 - 右上角 -->
        <div class="custom-controls">
            <!-- 底图切换 -->
            <div class="control-group">
                <h4>底图切换</h4>
                <button v-for="layer in baseLayers" :key="layer.name" @click="switchBaseLayer(layer.name)"
                    :class="['control-btn', { active: currentBaseLayer === layer.name }]">
                    {{ layer.title }}
                </button>
            </div>

            <!-- 地图操作 -->
            <div class="control-group">
                <h4>地图操作</h4>
                <button @click="resetView" class="control-btn">重置视图</button>
                <button @click="addMarker" class="control-btn">打点</button>
                <button @click="clearMarkers" class="control-btn">清除标记</button>
            </div>

            <!-- 控件开关 -->
            <div class="control-group">
                <h4>控件显示</h4>
                <button @click="toggleFullScreen" class="control-btn">全屏</button>
                <button @click="toggleScale" class="control-btn">
                    {{ scaleVisible ? '隐藏比例尺' : '显示比例尺' }}
                </button>
                <button @click="toggleMousePosition" class="control-btn">
                    {{ mousePositionVisible ? '隐藏坐标' : '显示坐标' }}
                </button>
            </div>
            <button @click="toShanxi" class="control-btn">
                去山西
            </button>
        </div>

        <div style="position: absolute;top: 0;left: 50px;">
            <a-button @click="toRemove('top')">向上移动</a-button>
            <a-button @click="toRemove('bottom')">向下移动</a-button>
            <a-button @click="toRemove('left')">向左移动</a-button>
            <a-button @click="toRemove('right')">向右移动</a-button>

        </div>
    </div>
</template>

<script>
import Map from 'ol/Map'
import View from 'ol/View'
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'
import { XYZ, Vector as VectorSource } from 'ol/source'
import { Feature } from 'ol'
import { LineString, Point, Circle } from 'ol/geom'
import { Style, Fill, Stroke } from 'ol/style'
import {
    defaults as defaultControls,
    Zoom,
    FullScreen,
    ScaleLine,
    MousePosition
} from 'ol/control'
import { unByKey } from 'ol/Observable'
import ImageLayer from 'ol/layer/Image';
import ImageStatic from 'ol/source/ImageStatic';
// 首先在顶部导入图片
import pic from '@/assets/zb.png';  // 确保图片路径正确
import GeoJSON from 'ol/format/GeoJSON.js';
import Icon from 'ol/style/Icon.js';
import Text from 'ol/style/Text.js';
import { fromLonLat } from 'ol/proj';  // 坐标转换
import { circular } from 'ol/geom/Polygon';
import Select from 'ol/interaction/Select.js';
import { pointerMove } from 'ol/events/condition'
// 方式一：单独导入 Draw
import Drawer from 'ol/interaction/Draw';
export default {
    name: 'MapComponent',
    data() {
        return {
            map: null,
            vectorSource: null,
            currentBaseLayer: 'gaode',
            markerCount: 0,
            scaleVisible: false,
            mousePositionVisible: false,
            scaleText: '',
            mousePositionText: '移动鼠标显示坐标',
            resolutionListener: null,
            pointerMoveListener: null,

            // 底图配置
            baseLayers: [
                {
                    name: 'gaode',
                    title: '高德地图',
                    layer: null
                },
                {
                    name: 'satellite',
                    title: '影像地图',
                    layer: null
                },
                {
                    name: 'tianditu',
                    title: '天地图',
                    layer: null
                }
            ]
        }
    },

    mounted() {
        this.$nextTick(() => {
            this.initMap()
        })
    },

    beforeUnmount() {
        this.destroyMap()
    },

    methods: {
        toRemove(data) {

            let center = this.map.getView().getCenter()
            switch (data) {
                case 'top':
                    center[1] += 0.1
                    break;
                case 'bottom':
                    center[1] -= 0.1
                    break;
                case 'left':
                    center[0] -= 0.1
                    break;
                case 'right':
                    center[0] += 0.1
                    break;
                default:
                    break;
            }
            this.map.getView().setCenter(center)
        },
        /**
         * 将地图视图中心定位到山西省
         * 
         * @description 该函数用于将地图的显示中心设置到山西省的地理位置坐标
         * @returns {void}
         */
        toShanxi() {
            // this.map.getView().setCenter([112.5492, 37.8570])
            this.map.getView().animate({
                center: [112.5492, 37.8570],
                zoom: 5,
                duration: 500
            })

        },
        /**
         * 初始化地图
         */
        initMap() {
            // 清理旧地图
            this.destroyMap()

            // 初始化底图
            const gaodeLayer = new TileLayer({
                source: new XYZ({
                    url: 'https://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                })
            })

            const satelliteLayer = new TileLayer({
                source: new XYZ({
                    url: 'https://webst0{1-4}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
                    crossOrigin: 'anonymous'
                }),
                visible: false
            })
            //天地图 瓦片

            const tiandituLayer = new TileLayer({
                source: new XYZ({
                    //
                    // url: 'http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0071230dde2e6f0b3bdb41776b633bb4',

                    url: 'http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=0071230dde2e6f0b3bdb41776b633bb4',


                    crossOrigin: 'anonymous'

                }),

                visible: false
            })
            // 创建矢量图层（用于标记）
            this.vectorSource = new VectorSource()
            const vectorLayer = new VectorLayer({
                source: this.vectorSource
            })


            // 存储图层引用
            this.baseLayers.find(l => l.name === 'gaode').layer = gaodeLayer
            this.baseLayers.find(l => l.name === 'satellite').layer = satelliteLayer
            this.baseLayers.find(l => l.name === 'tianditu').layer = tiandituLayer


            // 创建自定义缩放控件（中文提示）
            const zoomControl = new Zoom({
                zoomInTipLabel: '放大',
                zoomOutTipLabel: '缩小',
                duration: 250
            })

            // 创建全屏控件（中文提示）
            const fullScreenControl = new FullScreen({
                tipLabel: '切换全屏模式',
                label: '⛶'
            })


            const vecLayer = new VectorLayer({
                source: new VectorSource(),
                style: new Style({
                    stroke: new Stroke({
                        color: 'red',
                        width: 4
                    })
                })
            })
            // 创建地图
            this.map = new Map({ // 添加这个配置

                target: this.$refs.mapContainer,
                layers: [gaodeLayer, satelliteLayer, tiandituLayer, vectorLayer, vecLayer],
                view: new View({
                    center: [116.3974, 39.9093],
                    zoom: 3,
                    minZoom: 3,
                    maxZoom: 18,
                    // projection: 'EPSG:4326'
                }),
                controls: defaultControls({
                    attribution: true,
                    zoom: false, // 禁用默认缩放，使用自定义的
                    rotate: false
                }).extend([
                    zoomControl,
                    fullScreenControl
                ]),
                canvas: {
                    willReadFrequently: true
                },
            })

            // const vectorSource1 = new VectorSource({
            //     features: []
            // })
            // const vectorLayer1 = new VectorLayer({
            //     source: vectorSource1
            // })
            // let lineArr = []
            // this.map.addLayer(vectorLayer1)
            // this.map.on('click', function (e) {
            //     console.log(e.coordinate);

            //     vectorSource1.clear()
            //     let coordinate = e.coordinate
            //     lineArr.push(coordinate)
            //     console.log(lineArr);

            //     if (lineArr.length === 2) {
            //         console.log(2);

            //         let lineFeature = new Feature({
            //             geometry: new LineString(lineArr)
            //         });
            //         lineFeature.setStyle(
            //             new Style({
            //                 stroke: new Stroke({
            //                     color: 'red',
            //                     width: 8
            //                 })
            //             })
            //         )
            //         vectorSource1.addFeature(lineFeature)
            //         lineArr = []
            //     }
            // })



            // const circleFeature = new Feature({
            //     geometry: new Circle([116.3974, 39.9093], 1)

            // })

            // circleFeature.setStyle(
            //     new Style({
            //         fill: new Fill({
            //             color: 'red'
            //         })
            //     })
            // )

            // const vectorSource11 = new VectorSource({
            //     features: [circleFeature]
            // })
            // const vectorLayer11 = new VectorLayer({
            //     source: vectorSource11
            // })
            // this.map.addLayer(vectorLayer11)
            // const vectorSource3 = new VectorSource({
            //     url: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
            //     format: new GeoJSON()
            // })

            // //geojson数据加载
            // const vectorLayer33 = new VectorLayer({
            //     source: vectorSource3,
            //     style: new Style({
            //         stroke: new Stroke({
            //             color: 'red',
            //             width: 2
            //         }),
            //         fill: new Fill({
            //             color: 'rgba(255, 0, 0, 0.1)'
            //         })
            //     })

            // })


            // this.map.addLayer(vectorLayer33)

            // const select1 = new Select({
            //     condition: pointerMove
            // })
            // this.map.addInteraction(select1)
            // select1.on('select', function (e) {
            //     const f = e.selected[0]

            //     f?.setStyle(
            //         new Style({
            //             fill: new Fill({
            //                 color: 'green'
            //             })
            //         })
            //     )
            // })


            const draw = new Drawer({
                type: 'LineString',
                source: vecLayer.getSource()
            })
            this.map.addInteraction(draw)



            // 手动创建比例尺和坐标显示
            this.createScaleLine()
            this.createMousePosition()

            // 确保地图正确渲染
            this.$nextTick(() => {
                setTimeout(() => {
                    if (this.map) {
                        this.map.updateSize()
                    }
                }, 100)
            })



        },

        /**
         * 手动创建比例尺显示
         */
        createScaleLine() {
            // 监听地图分辨率变化来更新比例尺
            this.resolutionListener = this.map.getView().on('change:resolution', () => {
                if (this.scaleVisible) {
                    this.updateScaleLine()
                }
            })
        },

        /**
         * 更新比例尺显示
         */
        updateScaleLine() {
            const view = this.map.getView()
            const resolution = view.getResolution()
            const units = view.getProjection().getUnits()

            let scale
            if (units === 'degrees') {
                // 经纬度投影的比例尺计算
                const inchesPerMeter = 39.37
                const dpi = 96
                scale = resolution * 2.54 * dpi * 100000 / (0.0254 * 111320)
            } else {
                // 米制投影的比例尺计算
                const dpi = 25.4 / 0.28
                scale = resolution * dpi * 39.37
            }

            if (scale >= 1000) {
                this.scaleText = `1:${Math.round(scale / 1000)}千`
            } else {
                this.scaleText = `1:${Math.round(scale)}`
            }
        },

        /**
         * 手动创建鼠标坐标显示
         */
        createMousePosition() {
            this.pointerMoveListener = this.map.on('pointermove', (evt) => {
                if (this.mousePositionVisible) {
                    const coordinate = evt.coordinate
                    this.mousePositionText = `经度: ${coordinate[0].toFixed(4)}, 纬度: ${coordinate[1].toFixed(4)}`
                }
            })
        },

        /**
         * 切换底图
         */
        switchBaseLayer(layerName) {


            if (this.currentBaseLayer !== layerName && this.map) {
                // 隐藏所有底图
                this.baseLayers.forEach(layerConfig => {
                    layerConfig.layer.setVisible(false)

                })
                // 显示选中的底图
                this.baseLayers.find(l => l.name === layerName).layer.setVisible(true)
                // 更新当前底图状态
                this.currentBaseLayer = layerName

                // 确保地图正确渲染
                // this.map.updateSize()
            }


        },

        /**
         * 重置视图
         */
        resetView() {
            if (this.map) {
                this.map.getView().animate({
                    center: [116.3974, 39.9093],
                    zoom: 10,
                    duration: 500
                })
            }
        },

        /**
         * 添加标记
         */
        addMarker() {
            if (!this.map || !this.vectorSource) return

            this.markerCount++

            // 获取地图中心点
            const center = this.map.getView().getCenter()

            // 创建标记样式（红色圆点）
            const markerStyle = new Style({
                image: new Circle({
                    radius: 6,
                    fill: new Fill({ color: '#ff0000' }),
                    stroke: new Stroke({ color: '#ffffff', width: 2 })
                })
            })

            // 创建标记
            const marker = new Feature({
                geometry: new Point(center)
            })
            marker.setStyle(markerStyle)

            // 添加到地图
            this.vectorSource.addFeature(marker)
        },

        /**
         * 清除所有标记
         */
        clearMarkers() {
            if (this.vectorSource) {
                this.vectorSource.clear()
                this.markerCount = 0
            }
        },

        /**
         * 切换全屏
         */
        toggleFullScreen() {
            const mapElement = this.$refs.mapContainer
            if (!document.fullscreenElement) {
                mapElement.requestFullscreen?.()
            } else {
                document.exitFullscreen?.()
            }
        },

        /**
         * 切换比例尺显示
         */
        toggleScale() {
            this.scaleVisible = !this.scaleVisible
            if (this.scaleVisible) {
                this.updateScaleLine()
            }
        },

        /**
         * 切换鼠标坐标显示
         */
        toggleMousePosition() {
            this.mousePositionVisible = !this.mousePositionVisible
            if (this.mousePositionVisible) {
                this.mousePositionText = '移动鼠标显示坐标'
            }
        },

        /**
         * 销毁地图
         */
        destroyMap() {
            // 移除事件监听
            if (this.resolutionListener) {
                unByKey(this.resolutionListener)
                this.resolutionListener = null
            }

            if (this.map && this.pointerMoveListener) {
                this.map.un('pointermove', this.pointerMoveListener)
                this.pointerMoveListener = null
            }

            if (this.map) {
                this.map.setTarget(null)
                this.map = null
            }
            if (this.vectorSource) {
                this.vectorSource.clear()
                this.vectorSource = null
            }
            this.markerCount = 0
        }
    }
}
</script>

<style scoped>
.map-page {
    position: relative;
    width: 100%;
    height: 100%;
    min-height: 500px;
}

.map-container {
    width: 100%;
    height: 100%;
    background: #f0f0f0;
}

/* 自定义控制面板 - 右上角 */
.custom-controls {
    position: absolute;
    top: 70px;
    right: 10px;
    z-index: 1000;
    background: rgba(255, 255, 255, 0.95);
    padding: 12px;
    border-radius: 8px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    min-width: 150px;
    border: 1px solid #e0e0e0;
    backdrop-filter: blur(5px);
}

.control-group {
    margin-bottom: 12px;
}

.control-group:last-child {
    margin-bottom: 0;
}

.control-group h4 {
    margin: 0 0 6px 0;
    font-size: 12px;
    color: #333;
    font-weight: 600;
    border-bottom: 1px solid #eee;
    padding-bottom: 4px;
}

.control-btn {
    display: block;
    width: 100%;
    padding: 6px 8px;
    margin-bottom: 4px;
    border: 1px solid #ddd;
    background: #f8f9fa;
    border-radius: 4px;
    cursor: pointer;
    font-size: 11px;
    transition: all 0.2s ease;
    text-align: center;
    font-family: inherit;
    line-height: 1.2;
}

.control-btn:hover {
    background: #e9ecef;
    border-color: #adb5bd;
    transform: translateY(-1px);
}

.control-btn.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

.control-btn:last-child {
    margin-bottom: 0;
}

/* 控件显示容器 */
.control-display {
    position: absolute;
    background: rgba(255, 255, 255, 0.95);
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 11px;
    border: 1px solid #ccc;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    font-family: 'Microsoft YaHei', Arial, sans-serif;
    z-index: 999;
    backdrop-filter: blur(5px);
    line-height: 1.2;
}

#scale-line {
    bottom: 40px;
    left: 10px;
    min-width: 60px;
    text-align: center;
    font-weight: 500;
}

#mouse-position {
    bottom: 10px;
    right: 10px;
    min-width: 160px;
    text-align: center;
    white-space: nowrap;
    font-weight: 500;
}

/* 修复 OpenLayers 默认控件样式 */
:deep(.ol-zoom) {
    top: 10px;
    left: 10px;
}

:deep(.ol-zoom .ol-zoom-in) {
    border-radius: 4px 4px 0 0;
}

:deep(.ol-zoom .ol-zoom-out) {
    border-radius: 0 0 4px 4px;
}

:deep(.ol-attribution) {
    right: 10px;
    bottom: 10px;
    left: auto;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 2px 6px;
    font-size: 10px;
    max-width: calc(100% - 180px);
}

:deep(.ol-attribution ul) {
    margin: 0;
    padding: 0;
    color: #666;
}

:deep(.ol-attribution li) {
    display: inline;
    margin: 0 3px;
}

:deep(.ol-full-screen) {
    top: 10px;
    right: 10px;
    left: auto;
}

:deep(.ol-control button) {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #ccc;
}

:deep(.ol-control button:hover) {
    background: rgba(255, 255, 255, 1);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .custom-controls {
        top: 60px;
        right: 5px;
        padding: 8px;
        min-width: 130px;
    }

    .control-group h4 {
        font-size: 11px;
    }

    .control-btn {
        font-size: 10px;
        padding: 4px 6px;
    }

    #mouse-position {
        min-width: 140px;
        font-size: 10px;
    }

    #scale-line {
        font-size: 10px;
    }
}

/* 全屏模式下的样式调整 */
:fullscreen .custom-controls {
    top: 20px;
    right: 20px;
    padding: 15px;
}

:fullscreen .control-group h4 {
    font-size: 13px;
}

:fullscreen .control-btn {
    font-size: 12px;
    padding: 8px 12px;
}
</style>